package cc.orange.mainView;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
//import com.tendcloud.tenddata.TalkingDataSDK;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import cc.orange.BuildConfig;
import cc.orange.R;
import cc.orange.adapter.MsgCon4KFAdapter;
import cc.orange.adapter.MsgConAdapter;
import cc.orange.base.BaseActivity;
import cc.orange.databinding.ActivityConvekfBinding;
import cc.orange.databinding.ActivityConversationListBinding;
import cc.orange.entity.BaseEntity;
import cc.orange.entity.IsLoginsEntity;
import cc.orange.entity.KFChatListEntity;
import cc.orange.entity.UpdataUserPostEntity;
import cc.orange.http.ApiService;
import cc.orange.utils.ScreenUtils;
import cc.orange.utils.SoftKeyBoardListener;
import cc.orange.utils.ZXToastUtil;
import cc.orange.utils.emojis.EmoticonBoard;
import cc.orange.utils.emojis.RongUtils;
import demo.smart.access.xutlis.util.ZXAppUtil;
import demo.smart.access.xutlis.util.ZXSystemUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class Conver4KFActivity extends BaseActivity implements View.OnClickListener{

    private ActivityConvekfBinding binding;
    private String uid;

    private MsgCon4KFAdapter adapter;
    private List<KFChatListEntity.Data> list = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_convekf);
        binding.converListTitle1.setText("客服");
        initViews();
        getKeyBoard();
        getKeFuChat();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            list.clear();
            getKeFuChat();
        }
    };

    private void initViews() {
        RelativeLayout.LayoutParams pp = new RelativeLayout.
                LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ScreenUtils.getStatusBarHeight(Conver4KFActivity.this));
        binding.talktabTop.setLayoutParams(pp);

        binding.inputPanelEmojiBtn.setOnClickListener(this);
        binding.msginfoBack.setOnClickListener(this);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//        linearLayoutManager.setStackFromEnd(true);
        binding.talkMsgList.setLayoutManager(linearLayoutManager);
        adapter = new MsgCon4KFAdapter(list,1);
        binding.talkMsgList.setAdapter(adapter);

        TextWatcher mTextWatcher = new TextWatcher() {
            private int start;
            private int count;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
//                if (AndroidEmoji.isEmoji(s.subSequence(start, start + count).toString())) {
//                    binding.editBtn.removeTextChangedListener(this);
//                    String resultStr = AndroidEmoji.replaceEmojiWithText(s.toString());
//                    binding.editBtn.setText(AndroidEmoji.ensure(resultStr), TextView.BufferType.SPANNABLE);
//                    binding.editBtn.setSelection(binding.editBtn.getText().length());
//                    binding.editBtn.addTextChangedListener(this);
//                }
//                String s1 = binding.editBtn.getText().toString();
//                if(TextUtils.isEmpty(s1)){
//                    binding.talkSend.setBackgroundResource(R.drawable.shape_8e_13);
//                }else{
//                    binding.talkSend.setBackgroundResource(R.drawable.shape_home_title);
//                }
            }
        };

        binding.talkSend.addTextChangedListener(mTextWatcher);


        binding.talkSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s1 = binding.editBtn.getText().toString();
                if(!TextUtils.isEmpty(s1)){
                    returnKefu(s1);
                    forceSetSoftInputKeyBoard(false);
                    binding.editBtn.setText("");
                }
            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
//        EventBus.getDefault().post(new IsLoginsEntity(true));
//        TalkingDataSDK.onPageEnd(this, getLocalClassName());
    }

    public void forceSetSoftInputKeyBoard(boolean isShow) {
        InputMethodManager imm = (InputMethodManager) getApplication().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            if (isShow) {
                binding.editBtn.requestFocus();
                imm.showSoftInput(binding.editBtn, 0);
            } else {
                imm.hideSoftInputFromWindow(binding.editBtn.getWindowToken(), 0);
                binding.editBtn.clearFocus();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.input_panel_emoji_btn:
                forceSetSoftInputKeyBoard(false);
                EmoticonBoard mEmoticonBoard = new EmoticonBoard(Conver4KFActivity.this, binding.talkeRel1, "123",binding.editBtn);
                binding.converRel1.removeAllViews();
                binding.converRel1.addView(mEmoticonBoard.getView());

                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.converRel1.getLayoutParams();
                layoutParams.height = RongUtils.dip2px(230);
                binding.converRel1.setLayoutParams(layoutParams);
                break;
            case R.id.msginfo_back:
                finish();
                break;
        }
    }


    public void getKeyBoard(){

        //监听软键盘弹出，并获取软键盘高度
        SoftKeyBoardListener.setListener(Conver4KFActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                //软键盘弹起事件  并给View设置高度
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) binding.converRel1.getLayoutParams();
                layoutParams.height = RongUtils.dip2px(0);
                binding.converRel1.setLayoutParams(layoutParams);
            }

            @Override
            public void keyBoardHide(int height) {
                //软键盘隐藏事件  并给View设置高度为0
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
//        TalkingDataSDK.onPageBegin(this, getLocalClassName());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(0);
    }

    //
    private void getKeFuChat(){
        RetrofitFactory.create(ApiService.class)
                .getKeFuChat(getTokens())
                .enqueue(new DefaultCallback<KFChatListEntity>() {
                    @Override
                    public void onStart(Call<KFChatListEntity> call) {
                    }

                    @Override
                    public void onError(Call<KFChatListEntity> call, HttpError error) {
                        handler.sendEmptyMessageDelayed(0,10000);
                    }

                    @Override
                    public void onSuccess(Call<KFChatListEntity> call, KFChatListEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            list.addAll(baseEntity.getData());
                            adapter.notifyDataSetChanged();
                            if(list.size() > 1) {
                                binding.talkMsgList.smoothScrollToPosition(adapter.getItemCount() - 1);
                            }
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                        handler.sendEmptyMessageDelayed(0,10000);
                    }
                });
    }

    // 发消息给客服
    private void returnKefu(String content){

        String s = "{\"text\":\""+content+"\"}";
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("application/json"), s.toString());

        RetrofitFactory.create(ApiService.class)
                .returnKefu(getTokens(),requestBody1)
                .enqueue(new DefaultCallback<BaseEntity>() {
                    @Override
                    public void onStart(Call<BaseEntity> call) {

                    }

                    @Override
                    public void onError(Call<BaseEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){
                            KFChatListEntity.Data ll = new KFChatListEntity.Data();
                            ll.setText(content);
                            ll.setClassify(0);
                            list.add(ll);
                            adapter.notifyDataSetChanged();
                            if(list.size() > 1) {
                                binding.talkMsgList.smoothScrollToPosition(adapter.getItemCount() - 1);
                            }
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }
}